import { ref } from 'vue'
import { useAuthStore } from '../stores/auth.store'

interface WebSocketMessage {
  type: string
  data: any
}

class WebSocketService {
  private socket: WebSocket | null = null
  private url: string = import.meta.env.VITE_WEBSOCKET_URL || 'ws://localhost:8080/ws'
  public messages = ref<WebSocketMessage[]>([])
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5

  connect(userId: string) {
    const authStore = useAuthStore()
    const token = authStore.getToken()

    try {
      this.socket = new WebSocket(`${this.url}?userId=${userId}&token=${token}`)

      this.socket.onopen = () => {
        console.log('WebSocket connection established')
        this.reconnectAttempts = 0
      }

      this.socket.onmessage = (event) => {
        const message: WebSocketMessage = JSON.parse(event.data)
        this.messages.value.push(message)
      }

      this.socket.onclose = (event) => {
        console.log('WebSocket connection closed', event)
        this.reconnect()
      }

      this.socket.onerror = (error) => {
        console.error('WebSocket error', error)
        this.reconnect()
      }
    } catch (error) {
      console.error('WebSocket connection failed', error)
    }
  }

  private reconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      const delay = Math.pow(2, this.reconnectAttempts) * 1000
      
      setTimeout(() => {
        const authStore = useAuthStore()
        const userId = authStore.user?.id
        
        if (userId) {
          this.connect(userId)
        }
      }, delay)
    } else {
      console.error('Max reconnect attempts reached')
    }
  }

  disconnect() {
    if (this.socket) {
      this.socket.close()
      this.socket = null
    }
  }

  sendMessage(message: WebSocketMessage) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(message))
    } else {
      console.error('WebSocket is not connected')
    }
  }
}

export const websocketService = new WebSocketService()
